import io

from app.libs.captchas_codes.get_captcha import generate_random, generate_captcha_image
from app.libs.redprint import Redprint
from flask import make_response, session

api = Redprint('cache')


@api.route('', methods=['GET'])
def generate_captcha():
    random_str = generate_random()
    img = generate_captcha_image(random_str)
    buf = io.BytesIO()
    # 使用JPEG格式保存图像，然后在HTTP响应中返回图像数据
    img.save(buf, 'JPEG', quality=70)
    buf_str = buf.getvalue()
    response = make_response(buf_str)
    response.headers['Content-Type'] = 'image/jpeg'
    response.headers['Captcha'] = random_str.lower()
    # 将生成的验证码字符串存入session
    return response
